package com.md.youyouhui.ui.login;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.md.youyouhui.R;
import com.md.youyouhui.databinding.FragmentRegisterBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.NetWorkConstant;
import com.md.youyouhui.net.response.RegisterResponse;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.ui.MainActivity;
import com.md.youyouhui.ui.home.WebNewsActivity;
import com.md.youyouhui.utils.GlideApp;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.StatusBarHelper;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;
import com.umeng.analytics.MobclickAgent;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * Created by AdministratorZJ
 * on 2019/4/3.
 */
public class RegisterActivity extends BaseActivity {
    private FragmentRegisterBinding registerBinding;
    private MainViewModel viewModel;
    private Timer timer = new Timer();
    private TimerTask timerTask;
    private int time = 60;
    String token = "";
    @Override
    public void setContentLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StatusBarHelper.setFullWindow(getWindow());
            StatusBarHelper.setStatusBarTextColor(getWindow(), false);
        }
        registerBinding = DataBindingUtil.setContentView(this, R.layout.fragment_register);
        viewModel = new MainViewModel();
    }

    @Override
    public void initView() {
        registerBinding.timeCode.setOnClickListener(v -> {
            sendCodeService();
        });
        token = UUID.randomUUID().toString();
        GlideApp.with(this).load(NetWorkConstant.BASE_URL+"account/captcha?token="+token).error(R.drawable.code).into(registerBinding.mCode);
        registerBinding.registerBtn.setOnClickListener(v -> registerAccount());
        registerBinding.registerText.setOnClickListener(v ->
                startActivity(new Intent(this, WebNewsActivity.class).putExtra("url", NetWorkConstant.BASE_URL_HTTP+"9512/api/invited/agreement")));
    }

    @Override
    public void initData() {
        registerBinding.loginFinish.setOnClickListener(v -> finish());
        registerBinding.back.setOnClickListener(v -> finish());
    }

    private void sendCodeService() {
        String phone = registerBinding.registerPhone.getText().toString();

        String imgCode = registerBinding.imgCode.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(imgCode)) {
            Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        viewModel.sendCodeV2(phone,token,imgCode).observe(this, codeResponse -> {
            assert codeResponse != null;
            switch (codeResponse.status) {
                case LOADING:
                    break;
                case SUCCESS:
                    sendCode();
                    break;
                case ERROR:
                    ToastUtils.errMake(this, codeResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void registerAccount() {
        String phone = registerBinding.registerPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        String pass = registerBinding.registerPass.getText().toString();
        if (TextUtils.isEmpty(pass)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        String code = registerBinding.registerCode.getText().toString();
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        String requestPhone = registerBinding.requestPhone.getText().toString();
        viewModel.register(phone, code, pass, Constants.SOURCE, requestPhone).observe(this, objectResource -> {
            assert objectResource != null;
            switch (objectResource.status) {
                case LOADING:
                    registerBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    registerBinding.progress.setVisibility(View.GONE);
                    RegisterResponse data = objectResource.data;
                    if (null == data) {
                        Toast.makeText(this, "服务器没有返回token", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    SharedPreferencesUtils.saveString(this, Constants.USER_TOKEN, data.token);
                    SharedPreferencesUtils.saveString(this, Constants.INVITED_CODE, data.invitedCode);
                    Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                    //注册
                    MobclickAgent.onEvent(this, "Reg");
                    SharedPreferencesUtils.saveString(this, Constants.PHONE, phone);
                    startActivity(new Intent(this, MainActivity.class));
                    setResult(RESULT_OK);
                    finish();
                    break;
                case ERROR:
                    registerBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, objectResource.errorCode);
                    break;
                default:
                    registerBinding.progress.setVisibility(View.GONE);
                    break;
            }
        });
    }

    private void sendCode() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                time--;
                runOnUiThread(() -> {
                    registerBinding.timeCode.setText(String.format("%dS", time));
                    if (time == 0) {
                        time = 60;
                        registerBinding.timeCode.setText("发送验证码");
                        registerBinding.timeCode.setEnabled(true);
                        timerTask.cancel();
                    } else {
                        registerBinding.timeCode.setEnabled(false);
                    }
                });
            }
        };
        timer.schedule(timerTask, 100, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null == timer) {
            return;
        }
        if (null != timerTask) {
            timerTask.cancel();
        }
        timer.purge();
        timer.cancel();
    }

}
